package com.springboot.util.base;

import com.springboot.ding.monitor.MonitorUtil;
import com.springboot.util.config.MyProperties;
import com.springboot.util.uuid.DbUtilUuid;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

//import jakarta.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @description:
 * @author: zyj
 * @create: 2020-08-06 09:26
 **/
public class SpringBootBaseController {


    @Resource
    private MyProperties myProperties;
    @Resource
    private DbUtilUuid dbUtilUuid;

    public Long getDataId(){
        return dbUtilUuid.getDatabaseId();
    }


    public void errorMonitor(Exception e, String message, Logger logger){
        MonitorUtil.sendMessageTextStr(e, message, logger, myProperties.isSendDing(), myProperties.isSendCat());
    }

    public HttpServletResponse getHttpServletResponse(){
        try {
            if (RequestContextHolder.getRequestAttributes()==null){
                return null;
            }
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }


    public HttpServletRequest getHttpServletRequest() {
        try {
            if (RequestContextHolder.getRequestAttributes()==null){
                return null;
            }
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public Map<String, String> getHeaders(){
        return getHeaders(getHttpServletRequest());
    }

    public Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        if (request==null){
            return map;
        }
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

}
